<template>
	<div class="app-container">
		<div class="filter-container">
			<div class="fr">
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">添加</el-button>
      <!-- <el-button class="filter-item" style="margin-left: 10px;" @click="handleDelete" type="danger" icon="el-icon-delete">删除</el-button> -->
      </div>
    </div>
		<el-table class="tqd_table" :key='tableKey' :data="list" v-loading="listLoading" border fit highlight-current-row style="width: 100%;">
			<el-table-column width="60" label="序号" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="角色名称" show-overflow-tooltip prop="roleName">
      </el-table-column>
      <el-table-column label="角色关键字" show-overflow-tooltip prop="roleKey">
      </el-table-column>
      <el-table-column label="状态" show-overflow-tooltip prop="status">
				<template slot-scope="scope">
					<el-tag v-if="scope.row.status===0" type="success">正常</el-tag>
					<el-tag v-if="scope.row.status===1" type="danger">停用</el-tag>
          <el-tag v-if="scope.row.status===2" type="danger">隐藏</el-tag>
				</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="300" class-name="small-padding fixed-width">
        <template slot-scope="scope">
        	<el-button size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="listQuery.pageNum" :page-sizes="[15,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" width="550px">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="100px" style='width: 100%; '>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName"></el-input>
        </el-form-item>
        <el-form-item prop="roleKey" label="角色关键字">
					<el-input v-model="temp.roleKey"></el-input>
        </el-form-item>
				<el-form-item prop="refereeMode" label="状态">
					<el-radio-group v-model="temp.status">
						<el-radio :label="0">正常</el-radio>
						<el-radio :label="1">停用</el-radio>
					</el-radio-group>
        </el-form-item>
        <el-form-item prop="menuIdList" label="角色权限">{{temp.menuIdList}}
          <el-tree :data="menuTree" :props="defaultProps" node-key="id" :default-checked-keys="temp.menuIdList" ref="menuTree" show-checkbox @check-change="handleCheckChange"></el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
	</div>
</template>
<script>
import { saveRole, updateRole, getRoleList, getRoleInfo, deleteRole } from '@/api/role'
import { getMenuList } from '@/api/menu'
import waves from '@/directive/waves' // 水波纹指令
import { showMsg } from '@/utils'
export default {
  name: 'complexTable',
  directives: {
    waves
  },
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      menuTree: [],
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        pageNum: 1,
        pageSize: 15
      },
      temp: {
        id: undefined,
        roleName: null,
        roleKey: null,
        menuIdList: [],
        status: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '修改',
        create: '添加'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        roleName: [{ required: true, message: '必填', trigger: 'blur' }],
        roleKey: [{ required: true, message: '必填', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleCheckChange(data, checked, indeterminate) {
      this.temp.menuIdList = []
      this.temp.menuIdList = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
    },
    resetChecked() {
      if (this.temp.menuIdList.length > 0) {
        this.$refs.menuTree.setCheckedKeys([])
      }
    },
    getList() {
      this.listLoading = true
      getRoleList(this.listQuery).then(response => {
        this.list = response.data.data
        this.total = response.data.total
        this.listLoading = false
      })
    },
    getMenuList() {
      if (this.menuTree.length > 0) {
        return false
      } else {
        getMenuList().then(res => {
          this.menuTree = res.data.data
        })
      }
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleDelete(row) {
      this.$confirm('您确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var roleIds = [row.id]
        deleteRole(roleIds).then(res => {
          if (res.data.code === 0) {
            showMsg(res.data.message, 1)
            this.getList()
          } else {
            showMsg(res.data.message, 2)
          }
        })
      }).catch(() => {
        // console.log('===')
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        roleName: null,
        roleKey: null,
        menuIdList: [],
        status: 0
      }
    },
    handleCreate() {
      this.resetTemp()
      this.getMenuList()
      this.resetChecked()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.menuIdList = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
          saveRole(this.temp).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.getMenuList()

      getRoleInfo(row.id).then(res => {
        this.temp = {
          id: res.data.data.id,
          roleName: res.data.data.roleName,
          roleKey: res.data.data.roleKey,
          menuIdList: [],
          status: res.data.data.status
        }
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        console.log(this.menuTree)
        for (var i in res.data.data.menuIdList) {
          var isParent = this.menuTree.some((item, index) => {
            console.log(res.data.data.menuIdList[i], item.id)
            return item.id === res.data.data.menuIdList[i]
          })
          if (!isParent) {
            this.temp.menuIdList.push(res.data.data.menuIdList[i])
          }
        }
        this.$nextTick(() => {
          this.$refs.menuTree.setCheckedKeys(this.temp.menuIdList)
          this.$refs['dataForm'].clearValidate()
        })
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.menuIdList = this.$refs.menuTree.getCheckedKeys().concat(this.$refs.menuTree.getHalfCheckedKeys())
          const tempData = Object.assign({}, this.temp)
          updateRole(tempData).then(res => {
            if (res.data.code === 0) {
              this.dialogFormVisible = false
              showMsg(res.data.message, 1)
              this.getList()
            } else {
              showMsg(res.data.message, 2)
            }
          })
        }
      })
    }
    // handleDelete(row) {
    //   this.$prompt('请输入密码', '确认删除？', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消'
    //     // inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
    //     // inputErrorMessage: '邮箱格式不正确'
    //   }).then(({ value }) => {
    //     this.$message({
    //       type: 'success',
    //       message: '你的密码是: ' + value
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '取消输入'
    //     })
    //   })
    // }
  }
}
</script>